package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwt;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头token
        String token = request.getHeader(Constants.JWT_AUTHORITIES);

        //token为空 直接抛异常401
        if(token == null || token.equals("")){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        try {
            //解析token
            Claims claims = JwtUtil.parseJWT(jwt.getBase64EncodedSecretKey(), token);
            Long userId = (Long) claims.get(Constants.JWT_USERID);
            //解析成功将userId存入LocalThread中
            UserThreadLocal.set(userId);

            //获取当前请求方法和请求uri,并拼接
            String method = request.getMethod();
            String requestURI = method+request.getRequestURI();

            //获取到redis中的urls集合
            String s = redisTemplate.opsForValue().get(UserCacheConstant.USER_RESOURCE_LIST + userId);
            List<String> urls = JSONUtil.toList(s, String.class);

            //路径匹配
            AntPathMatcher antPathMatcher = new AntPathMatcher();

            for (String url : urls) {
                if(antPathMatcher.match(url,requestURI)){
                    return true;
                }
            }

        } catch (Exception e) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
